package org.piggy.common.utils;

import java.lang.reflect.Method;
import java.util.Properties;

public class PropertiesUtil {

    public static void properties2Object(Properties p, Object object, String prefix) {
        Method[] methods = object.getClass().getMethods();
        for (Method method : methods) {
            String mn = method.getName();
            if (mn.startsWith("set")) {
                try {
                    // set
                    String tmp = mn.substring(4);
                    //
                    String first = mn.substring(3, 4);

                    String key = prefix + first.toLowerCase() + tmp;
                    String property = p.getProperty(key);
                    if (property != null) {
                        Class<?>[] pt = method.getParameterTypes();
                        if (pt.length > 0) {
                            String cn = pt[0].getSimpleName();
                            Object arg;
                            switch (cn) {
                                case "int", "Integer" -> arg = Integer.parseInt(property);
                                case "long", "Long" -> arg = Long.parseLong(property);
                                case "double", "Double" -> arg = Double.parseDouble(property);
                                case "boolean", "Boolean" -> arg = Boolean.parseBoolean(property);
                                case "float", "Float" -> arg = Float.parseFloat(property);
                                case "String" -> arg = property;
                                default -> {
                                    continue;
                                }
                            }
                            method.invoke(object, arg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void properties2Object(Properties p, Object object) {
        properties2Object(p, object, "");
    }

}
